package org.javascud.extensions.cxf.zookeeper.client;

import org.apache.zookeeper.ZooKeeper;
import org.javascud.extensions.cxf.AbstractLoadBalanceStrategy;
import org.javascud.extensions.zookeeper.GroupMemberCenter;

import java.util.List;

/**
 * Fetch service from zookeeper.
 *
 * you can call this by a thread or refactory it for Quartz.
 *
 * @author Felix Zhang   Date:2010-10-16 01:13
 */
public class ServiceEndpointsFetcher extends Thread {

    private ZooKeeper zooKeeper;
    private String groupName;
    private AbstractLoadBalanceStrategy strategy;
    private int interval = 500;

    public void setInterval(int interval) {
        this.interval = interval;
    }

    public void setStrategy(AbstractLoadBalanceStrategy strategy) {
        this.strategy = strategy;
    }

    public void setZooKeeper(ZooKeeper zooKeeper) {
        this.zooKeeper = zooKeeper;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    @Override
    public void run() {
        fetchMemberData();
    }

    private void fetchMemberData() {
        if (zooKeeper != null) {
            GroupMemberCenter gmc = new GroupMemberCenter();
            gmc.setZooKeeper(zooKeeper);

            while (true) {
                List<String> serviceList = gmc.fetchGroupMembers(groupName);
                System.out.println("return service " + serviceList.size());
                strategy.setAlternateAddresses(serviceList);

                try {
                    sleep(interval);
                }
                catch (Exception e) {
                }
            }
        }
    }
}
